import wx from '../../../subwe/bridge';
import WXPage from "../../../subwe/page";
import { Index } from '../../../apis/index';
const app = getApp();
const API = new Index();
let proListToTop = [],
  menuToTop = [],
  MENU = 0,
  windowHeight,
  timeoutId;
WXPage({
  data: {
    menuList: [],
    activeIndex: "a1",
    toView: "a1",
    activeSpec: 0,
    specList: [{
      name: "5包 (新优惠)",
      key: 0
    }, {
      name: "12包 (限时特惠)",
      key: 1
    }, {
      name: "15包 (限时特惠)",
      key: 2
    }, {
      name: "6包 (新优惠)",
      key: 3
    }, {
      name: "15包 (限时特惠)",
      key: 4
    }],
    popupVisible: false,
    room: "",
    selectedGoodsVisible: false,
    imageUrl: `${app.globalData.imageUrl}/zhongman2`,
    goodsList: [],
    host: wx.getStorageSync("host"),
    cartList: [],
    totalPrice: 0,
    discountAmount: 0,
    goodsPosition: 0,
    currentActiveIndex: 0,
    StatusBar: app.globalData.StatusBar,
    rightGoodsList: [],
    goodsId: "",
    contentTop: 0,
    supermarketShow: true
  },
  onLoad() {
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#FFFFFF'
    });
    this.getroomNum();
  },
  // 获取房间号和设备号
  getroomNum() {
    if(!app.globalData.deviceSn) return wx.showToast({title: '请扫门店设备码', icon: 'none'})
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    API.getDeviceInfo({
      deviceSn: app.globalData.deviceSn
    }).then(res => {
      const {
        room,
        placeId
      } = res.result;
      this.setData({
        room: room,
        placeId: placeId
      });
      if (placeId) {
        this.getGoodsTypeInfo(placeId);
        this.getCartInfo();
      }
    }, () => {
      wx.hideLoading();
    });
  },
  // 查询商品类型
  getGoodsTypeInfo(placeId) {
    API.getGoodsType({
      placeId
    }).then(res => {
      console.log("类型==》res", res);
      let data = res.result;
      if (!data || data.length === 0) {
        this.setData({
          supermarketShow: false
        });
        wx.hideLoading();
        return;
      }
      this.data.menuList = data;
      data && this.getSupermarketGoodsInfo(placeId);
    }, () => {
      wx.hideLoading();
    });
  },
  calculation() {
    const {
      menuList,
      cartList,
      rightGoodsList
    } = this.data;
    const aray = rightGoodsList.map(i => ({
      ...i,
      number: 0
    }));
    cartList.forEach(k => {
      aray.forEach(item => {
        if (item.id === k.goodsId) item.number = k.buyNum;
      });
    });
    const list = menuList.map(i => ({
      ...i,
      options: []
    }));
    list.forEach(i => {
      aray.forEach(k => {
        i.typeName == k.typeName && i.options.push({
          ...k
        });
      });
    });
    this.setData({
      menuList: list
    });
  },
  // 获取超市商品信息
  getSupermarketGoodsInfo(placeId) {
    API.supermarketInfo({
      pageNo: 1,
      pageSize: 999,
      placeId
    }).then(res => {
      wx.hideLoading();
      let {
        data
      } = res.result;
      this.setData({
        rightGoodsList: data
      });
      this.calculation();
      // 确保页面数据已经刷新完毕~
      setTimeout(() => {
        this.getAllRects();
      }, 1000);
    }, () => {
      wx.hideLoading();
    });
  },
  changeMenu(e) {
    const id = Number(e.target.id);
    // 改变左侧tab栏操作
    if (id === this.data.currentActiveIndex) return;
    MENU = 1;
    const rightProTop = id !== 0 ? proListToTop[id - 1] : 0;
    this.setData({
      currentActiveIndex: id,
      rightProTop: rightProTop
    });
    console.log('changeMenu', e, id)
    this.setMenuAnimation(Number(id));
  },
  scroll(e) {
    for (let i = 0; i < proListToTop.length; i++) {
      if (e.detail.scrollTop < proListToTop[i] && i !== 0 && e.detail.scrollTop > proListToTop[i - 1]) {
        return this.setDis(i);
      }
    }
    // 找不到匹配项，默认显示第一个数据
    if (!MENU) {
      this.setData({
        currentActiveIndex: 0
      });
    }
    MENU = 0;
  },
  setDis(i) {
    // 设置左侧menu栏的选中状态
    if (i !== this.data.currentActiveIndex && !MENU) {
      this.setData({
        currentActiveIndex: i
      });
    }
    MENU = 0;
    this.setMenuAnimation(i);
  },
  setMenuAnimation(i) {
    // 设置动画，使menu滚动到指定位置。
    let self = this;
    if (menuToTop[i].animate) {
      // 节流操作
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      timeoutId = setTimeout(() => {
        self.setData({
          leftMenuTop: menuToTop[i].top - windowHeight + this.data.contentTop
        });
      }, 50);
    } else {
      if (this.data.leftMenuTop === 0) return;
      this.setData({
        leftMenuTop: 0
      });
    }
  },
  getActiveReacts() {
    wx.createSelectorQuery().selectAll('.menu-active').boundingClientRect().exec(rects => {
      return rects[0].top;
    });
  },
  getAllRects() {
    console.log('getAllRects')
    wx.createSelectorQuery().selectAll('.content').boundingClientRect().exec(rects => {
      console.log('.content', res)
      rects = rects[0] || []
      this.setData({
        contentTop: rects[0].top
      });
    });
    let value = 0;
    // 获取商品数组的位置信息
    wx.createSelectorQuery().selectAll('.pro-item').boundingClientRect().exec(rects => {
      rects = rects[0] || []
      rects.forEach(rect => {
        value += rect.height;
        // 这里减去44是根据你的滚动区域距离头部的高度，如果没有高度，可以将其删去
        proListToTop.push(value);
      });
    });
    // 获取menu数组的位置信息
    wx.createSelectorQuery().selectAll('.menu-item').boundingClientRect().exec(rects => {
      console.log('.menu-item', rects[0])
      rects = rects[0] || []
      wx.getSystemInfo({
        success: res => {
          windowHeight = res.windowHeight / 2;
          rects.forEach(rect => {
            menuToTop.push({
              top: rect.top,
              animate: rect.top > windowHeight
            });
          });
          console.log('menuToTop', menuToTop)
        }
      });
    });
  },
  // 获取系统的高度信息
  getSystemInfo() {
    wx.getSystemInfo({
      success: function (res) {
        windowHeight = res.windowHeight / 2;
      }
    });
  },
  // 选择规格 内容
  specClick(e) {
    this.setData({
      activeSpec: e.currentTarget.dataset.item.key
    });
  },
  // 关闭弹框
  closePopup() {
    this.setData({
      popupVisible: false
    });
  },
  // 选择规格 弹框
  chooseSpec() {
    this.setData({
      popupVisible: true
    });
  },
  // 加入购物车
  addCartClick() {
    this.setData({
      popupVisible: false
    });
  },
  // 去结算
  toSettleAccounts() {
    if (!wx.getStorageSync("login_key")) {
      API.getLoginToken().then(res => {
        if (!res) return;
        wx.setStorageSync("login_key", res.result);
        wx.setStorageSync("host", res.result.host);
      });
    }
    const {
      cartList
    } = this.data;
    if (cartList.length === 0) {
      wx.showToast({
        title: "暂无可结算商品",
        icon: "none"
      });
      return;
    }
    wx.navigateTo({
      url: `/pages/supermarket/submitOrder/submitOrder`
    });
  },
  closeMask() {
    this.setData({
      selectedGoodsVisible: false
    });
    this.calculation();
  },
  // 添加商品到购物车
  addShopToCart() {},
  showSelectGoods() {
    if (this.data.cartList.length === 0) return;
    this.setData({
      selectedGoodsVisible: true
    });
  },
  // 获取购物车列表信息
  getCartInfo() {
    API.getCartList({
      placeId: this.data.placeId
    }).then(res => {
      const {
        data
      } = res.result;
      let totalPrice = 0;
      let discountAmount = 0;
      const arr = data.map(i => {
        discountAmount += i.buyNum * i.discountAmount / 100;
        return i.buyNum * i.price / 100;
      });
      if (arr && arr.length > 0) {
        totalPrice = arr.reduce((prev, curr, idx, arr) => {
          return prev + curr;
        });
      } else {
        this.setData({
          selectedGoodsVisible: false
        });
      }
      this.setData({
        cartList: res.result.data,
        discountAmount: discountAmount.toFixed(2),
        totalPrice: (totalPrice - discountAmount).toFixed(2)
      });
      this.calculation();
    });
  },
  // 清空购物车
  clearCartGoods() {
    API.clearCart({
      placeId: this.data.placeId
    }).then(() => {
      this.getCartInfo();
      this.setData({
        selectedGoodsVisible: false
      });
    });
  },
  updateCartInfo() {
    this.getCartInfo();
  },
  gotoDetail(e) {
    wx.navigateTo({
      url: '/pages/supermarket/goodsDetail/goodsDetail?id=' + e.mark.id
      // url: '/pages/evaluateGift/priceDetail/priceDetail' + '?id=' + this.data.res.id
    });
  }
});
